import React, { Component } from 'react';
import { Card } from 'antd';
import Mutil from '../../util/mm.js';
import Product from '../../server/product-server.js';

const _mm = new Mutil();
const _product = new Product();

class Add extends Component{
	constructor(props){
		super(props);
		this.state = {
			categoryList   : [],
			parentId       : 0,
			categoryName   : ''
		}
	}
	componentDidMount(){
		this.loadCategoryList();
	}
	//表单的值发送变化
	onValuechange(e){
		let name = e.target.name,
			value = e.target.value;
			this.setState({
				[name] : value
			})
	}
	
	//加载品类列表,显示品类列表
	loadCategoryList(){
		_product.getCategoryList().then((res)=>{
			this.setState({
				categoryList: res
			});
		}, errMsg =>{
			_mm.errorTips(errMsg)
		});
	}
	//提交
	onSubmit(e){
		let categoryName = this.state.categoryName.trim();
		//如果商品品类名称不为空，提交数据
		if(categoryName){
			_product.saveCategory({
				parentId: this.state.parentId,
				categoryName: categoryName
			}).then(res => {
				_mm.successTips(res);
				this.props.history.push('/product/category');
			}, errMsg => {
				_mm.errorTips(errMsg);
			})
		}
		//否则，提示错误
		else{
			_mm.errorTips('	请输入品类名称')
		}
	}
		
	render() {
		return (
			<Card title="新增品类">
				<div className="row">
					<div className="col-md-12">
					    <div className="form-horizontal">
						<div className="form-group">
						    <label className="col-md-2 control-label">所属品类</label>
						    <div className="col-md-6">
						      <select 
						      	name="parentId"
						      	className="form-control"
						      	onChange ={(e) => this.onValuechange(e)}
						      	>
						      	<option value="0">根品类</option>
						      	{
						      		this.state.categoryList.map((category, index) => {
						      			return <option value={category.id} key={index}>根品类/{category.name}</option>
						      		})
						      	}
						      </select>
					    	</div>
					    </div>	
					    <div className="form-group">
						    <label className="col-md-2 control-label">品类名称</label>
						    <div className="col-md-6">
						      <input 
						      	type="text" 
						      	name="categoryName"
						      	value={this.state.name}
						      	className="form-control" 
						      	placeholder="请输入品类名称" 
						      	onChange={(e) => this.onValuechange(e)}
						      	/>
					    	</div>
						</div>
						<div className="form-group">
						    <div className="col-md-offset-2 col-sm-10">
						      <button 
						      	type="submit" 
						      	className="btn btn-default"
						      	onClick={(e)=>{this.onSubmit(e)}}
						      	>提交</button>
						    </div>
					  </div>
					  </div></div>
				</div>
			</Card>
		);
	}
}

export default Add;